How to use WMI to get GPU info? - winapi

I want to use wmi to get the GPU info in a program written in Go.I know use the https://godoc.org/github.com/StackExchange/wmi can do it,and here is a function named "func Query".But, i don't know how to edit the "query string".Somebody can help me ? Thanks!

import (
"github.com/StackExchange/wmi"
)
type gpuInfo struct {
Name string
}
func getGPUInfo() {
var gpuinfo []gpuInfo
err := wmi.Query("Select * from Win32_VideoController", &gpuinfo)
if err != nil {
return
}
fmt.Printf("gpu:",gpuinfo[0].Name)
}

Related

Creating and seeding a torrent in golang

I want to use the golang library https://github.com/anacrolix/torrent to create to torrent and get a magnet and seed the torrent. Below you can find the code I wrote. Yet, if I use the magnet the code generates I can not download anything not even the metainfo.
Am I missing something here?
package main
import (
"log"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/metainfo"
)
var builtinAnnounceList = [][]string{
{"http://p4p.arenabg.com:1337/announce"},
{"udp://tracker.opentrackr.org:1337/announce"},
{"udp://tracker.openbittorrent.com:6969/announce"},
}
func main() {
tmpComment:="Cool torrent description"
tmpCreatedBy:="coolboys"
tmpInfoName:="CoolInfoName"
mi := metainfo.MetaInfo{
AnnounceList: builtinAnnounceList,
}
mi.SetDefaults()
mi.Comment = tmpComment
mi.CreatedBy = tmpCreatedBy
//}
//mi.UrlList = args.Url//???????????
info := metainfo.Info{
PieceLength: 256 * 1024,
}
err := info.BuildFromFilePath("./TorrentFiles")//args.Root)
if err != nil {
log.Fatal(err)
}
info.Name =tmpInfoName
mi.InfoBytes, err = bencode.Marshal(info)
if err != nil {
log.Fatal(err)
}
tmpMagnet:=mi.Magnet(nil,nil)
log.Println("****",tmpMagnet)
//
cfg := torrent.NewDefaultClientConfig()
cfg.Seed = true
mainclient, ncerr := torrent.NewClient(cfg)
if ncerr != nil {
log.Println("new torrent client:", ncerr)
return
}
defer mainclient.Close()
t, _ := mainclient.AddMagnet(tmpMagnet.String())
for {
log.Println("******", t.Seeding())
time.Sleep(8 * time.Second)
}
}
I think you might need to take a closer look at this example. Among other things, I don't see any invocation of t.DownloadAll() to do the actual download or mainclient.WaitAll() to tell you when the downloads are complete.
I corrected the code I wrote and the correct code can be found here:
enter link description here
In the original code I should not have used addmagnet as it assumes that I don't have the info available, which is why it would fail to seed.

Go-github not retrieving tag names correctly

I have the following simple golang code which retrieves tags from terraform repository:
import (
"github.com/google/go-github/v48/github"
"context"
)
func main() {
client := github.NewClient(nil)
tags, _, _ := client.Repositories.ListTags(context.Background(), "hashicorp", "terraform", nil)
if len(tags) > 0 {
latestTag := tags[0]
fmt.Println(latestTag.Name)
} else {
fmt.Printf("No tags yet")
}
}
Which returns a strange hexadecimal value:
0x1400035c4a0
And I would want to return:
v1.4.0-alpha20221207
Following the official docs, the function ListTags should return the name encoded into a struct:
https://pkg.go.dev/github.com/google/go-github/github#RepositoriesService.ListTags
Many thanks
I did try to execute a simple GET request https://api.github.com/repos/hashicorp/terraform/tags and I can see that the github api returns the tags correctly
IDK why, but I realize the latestTag.Name is a pointer and what you're printing is the address of the memory: 0x1400035c4a0.
You just need to dereference it:
fmt.Println(*latestTag.Name)
Bonus, check error with if condition that is returned by the function call to avoid having to go something like this:
tags, response, err := client.Repositories.ListTags(context.Background(), "hashicorp", "terraform", nil)
fmt.Println(response)
if err != nil {
fmt.Println(err)
} else {
if len(tags) > 0 {
latestTag := tags[0]
fmt.Println(*latestTag.Name)
} else {
fmt.Printf("No tags yet")
}
}

Inputs on correct usage of binding:"required" in Golang struct

I have a struct (with 1 field, for simplification purpose here) for which data comes from another function.
Further, for the struct field, I have put binding:"required", as I need it to be non-empty/present.
Code:
package main
import (
"fmt"
"encoding/json"
)
type Config struct {
Name string `yaml:"name" json:"name" binding:"required"`
}
func main() {
var myConfig Config
var rawConfig = []byte(`{}`) // Empty, Nothing getting passed.
err := json.Unmarshal(rawConfig, &myConfig)
if err != nil {
panic(err)
}
fmt.Printf("Name = %s\n", myConfig.Name)
}
When I run this, even if Name value has not been passed in, it passes.
Output:
Name =
Go playground Code link : https://play.golang.org/p/zA6nij9vTvY
I want to achieve the following:
As I expect the 'Name' field to be present, what do I do to make it fail, if not present. Is unmarshalling not expected to use binding=required tag and fail ?
Else, whats the best approach to figure out if a required field is not present so that we fail ?
Or is the crude way of iterating on fields, and figuring out if empty, the only way ?
You might do this in hard way by iterating over struct fields using reflect, get the tags and parse them which is not advised unless you need some customizations.
Or you might like use available validator packages:
https://github.com/dealancer/validate
package main
import (
"encoding/json"
"fmt"
"gopkg.in/dealancer/validate.v2"
)
type Config struct {
Name string `yaml:"name" json:"name" validate:"empty=false"`
}
func main() {
var myConfig Config
var rawConfig = []byte(`{}`) // Empty, Nothing getting passed.
err := json.Unmarshal(rawConfig, &myConfig)
if err != nil {
panic(err)
}
err = validate.Validate(myConfig)
if err != nil {
panic(err)
}
fmt.Printf("Name = %s\n", myConfig.Name)
}

Error handling of executed slice of functions in Go

I must run an unknown number of functions in a for cycle and I want to create meaningful errors when something goes wrong (when error returns from one of them)
Here some code:
package storage
import (
"github.com/attilasatan/ankara/engine/indexer"
)
type NewHandler func(*indexer.Document) error
var NewHandlers []NewHandler
func AppendNewHandler(handler NewHandler) {
NewHandlers = append(NewHandlers, handler)
}
func New(document *indexer.Document) (err error) {
for i, handler := range NewHandlers {
err = handler(document)
if err != nil {
err = errors.New(`New Handler error at index ` + string(i) + `
original:
` + err.Error())
return
}
}
return
}
This is my solution for error handling but i don't feel comfortable with it because I only return the index of the function that I executed.
My question is. Can I collect more information about the function that returned not nil error.
Also any kind of advises would be appreciated.
Use a struct that contains the func and any metadata instead of just a func. Something like this.
type NewHandler struct {
Handler func(*indexer.Document) error
Data string // or whatever data
}
Also make sure your slice holds pointers because go is pass-by-value.
var NewHandlers []*NewHandler
Then when you for loop, it goes like this.
for i, handler := range NewHandlers {
err = handler.Handler(document)
....
And you can include your Data in the error.

Interface/Struct "Does not implement X, Wrong type or Method, not sure why I am getting this error

Hi guys fairly new to Golang, I understand that interfaces are kind of like contracts that guarantee that certain things will operate a certain way, thats cool and all, and if I make a local copy of it I can basically re-write how it operates (From what I understand, please correct me if I'm wrong)
Here is what I have so far
package register
import (
"log"
"net/http"
"github.com/yohcop/openid-go"
)
var nonceStore = &openid.SimpleNonceStore{
Store: make(map[string][]*openid.Nonce)}
var discoveryCache = &SimpleDiscoveryCache{}
type DiscoveredInfo interface {
OpEndpoint() string
OPLocalID() string
ClaimedID() string
}
type SimpleDiscoveredInfo struct {
opEndpoint, opLocalID, claimedID string
}
type SimpleDiscoveryCache map[string]DiscoveredInfo
func (s *SimpleDiscoveryCache) Put(id string, info DiscoveredInfo) {
db := common.ConnectDB()
rows, err := db.Query("INSERT INTO discovery_cache SET id=?, opendpoint=?, oplocalid=?, claimedid=?",
id, info.OpEndpoint(), info.OPLocalID(), info.ClaimedID())
if err != nil {
panic("Error: " + err.Error())
}
log.Println(rows)
}
func (s *SimpleDiscoveryCache) Get(id string) DiscoveredInfo {
db := common.ConnectDB()
rows, err := db.Query("SELECT FROM discovery_cache WHERE id=?", id)
if err != nil {
panic("Error: " + err.Error())
}
log.Println(rows)
var opEndpoint, opLocalID, claimedID string
for rows.Next() {
err := rows.Scan(&opEndpoint, &opLocalID, &claimedID)
if err != nil {
panic("Help!")
}
}
return &SimpleDiscoveredInfo{
opEndpoint, opLocalID, claimedID,
}
}
func DiscoverHandler(w http.ResponseWriter, r *http.Request) {
url, err := openid.RedirectURL("http://steamcommunity.com/openid", "http://localhost:1337/login/return", "http://localhost")
if err != nil {
http.Error(w, "Failed to login", 500)
}
http.Redirect(w, r, url, 303)
}
func CallbackHandler(w http.ResponseWriter, r *http.Request) {
fullUrl := "http://localhost:1337" + r.URL.String()
id, err := openid.Verify(fullUrl, discoveryCache, nonceStore)
if err != nil {
http.Error(w, "Failed", 500)
}
log.Println(id)
}
Basically I am trying to make my own DiscoveryCache so that it uses a database instead of memory for storage (as instructed to do by the Go-OpenID package located here: https://github.com/yohcop/openid-go
The part I'm trying to recreate is located here: https://github.com/yohcop/openid-go/blob/master/discovery_cache.go
Now I have done (what I assume) everything that should need doing to make this work, but I keep getting this error:
controllers/register/register.go:60: cannot use SimpleDiscoveredInfo literal (type *SimpleDiscoveredInfo) as type openid.DiscoveredInfo in return argument:
*SimpleDiscoveredInfo does not implement openid.DiscoveredInfo (missing ClaimedID method)
controllers/register/register.go:78: cannot use discoveryCache (type *SimpleDiscoveryCache) as type openid.DiscoveryCache in argument to openid.Verify:
*SimpleDiscoveryCache does not implement openid.DiscoveryCache (wrong type for Put method)
have Put(string, DiscoveredInfo)
want Put(string, openid.DiscoveredInfo)
If anybody could inform me on what I have done wrong that would be much appreciated. Thanks! If you need any more information please let me know.
SimpleDiscoveredInfo doesn't implement the interface's methods, you need something like this:
func (sdi *SimpleDiscoveredInfo) OpEndpoint() string { return sdi.opEndpoint }
func (sdi *SimpleDiscoveredInfo) OpLocalID() string { return sdi.opLocalID }
func (sdi *SimpleDiscoveredInfo) ClaimedID() string { return sdi.claimedID }
var _ openid.DiscoveredInfo = (*SimpleDiscoveredInfo)(nil)
http://play.golang.org/p/qVTTKfhNHu
For
controllers/register/register.go:78: cannot use discoveryCache (type *SimpleDiscoveryCache) as type openid.DiscoveryCache in argument to openid.Verify:
*SimpleDiscoveryCache does not implement openid.DiscoveryCache (wrong type for Put method)
have Put(string, DiscoveredInfo)
want Put(string, openid.DiscoveredInfo)
Your types need to return openid.DiscoveredInfo not DiscoveredInfo.

Resources