|
Disclaimer:
These pages about different languages / apis / best practices were mostly jotted down quckily and rarely corrected afterwards. The languages / apis / best practices may have changed over time (e.g. the facebook api being a prime example), so what was documented as a good way to do something at the time might be outdated when you read it (some pages here are over 15 years old). Just as a reminder. Software developer notes about Go (the google language, not the prolog like language)Developer notes for Go / golang
Save imagetoimg, _ := os.Create("/tmp/tmp.jpg") defer toimg.Close() jpeg.Encode(toimg, croppedImg, &jpeg.Options{jpeg.DefaultQuality}) Fetching content of urlsclient := &http.Client{} req, err := http.NewRequest("GET", url, nil) req.Header.Add("User-Agent", "an user agent for my go code") resp, err := client.Do(req) // alternatively just do: // resp, err := http.Get(s) if nil != err { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if nil != err { fmt.Println(err) return } fmt.Println("%s", string(body)) Converting//string to io.Reader r := strings.NewReader(str) //string to int and int to string import ( "strconv" ) i, err := strconv.Atoi(s) //int to string str := strconv.Itoa(123) parsing htmlfunc MyFunc(n *html.Node) { if n.Type == html.ElementNode && n.Data == "div" { for _, attr := range n.Attr { if attr.Key == "class" && attr.Val == "someclass" { fmt.Print("Found one ") break } } } for c := n.FirstChild; c != nil; c = c.NextSibling { MyFunc(c) } return } JsonStruct to jsonjpegMessage := sqspool.JpegMessage{"888"} b, err := json.Marshal(jpegMessage) if nil != err { l.Err("Failed nmarshal json from fillsqs: " + err.Error() ) return; } myAmz.GetQueue().SendMessage( string(b) ); json to structbyteArray := []byte(msgstr) var m JpegMessage err = json.Unmarshal(byteArray, &m) if nil != err { l.Err("Failed unmarshal json from sqs: " + err.Error() ) return; }json decoding in go Go and JSON Reading a filepath := "/tmp/go.txt" r, _ := os.Open(path) defer r.Close() //parse as html (takes io.Reader) doc, err := html.Parse(r) Writing a fileerr = ioutil.WriteFile(outputfilename, data, 0644) Pass N argumentsThe arguments are converted to a slice that you for example can do len() onfunc DumpStrings( strs ...string ) { for _, str := range strs { fmt.Println( str ); } } loggingUse log package to make sure the output wont get messed up by different goroutinesThe log in its simplest form can just call log.Println. It writes to STDERR as default. log.Println("hello")A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer. To convert the error message to string, call the Error() funciton, e.g. l.log("Something went wrong, here is the error: " + err.Error() ) ImportsUsed in imports to import stuff but we dont need to adress it in our code Blank Identifier _ in Import StatementVariable declarationsvar myvar = "golang"; //is the same as myvar := "golang"; adding methods to a structtype GoGoGo struct { } //private (lower case) func (cs *GoGoGo) hello() string { return "hello" } //public (upper case) func (cs *GoGoGo) Goodbye() string { return "goodbye"; } Amazon SQS and Go
S3 Getimport ( s3 "github.com/crowdmob/goamz/s3" ) data, err := bucket.Get( filename ) if nil != err{ return err } //save to file err = ioutil.WriteFile(outputfilename, data, 0644) if nil != err{ return err } S3 Putdata, err := ioutil.ReadFile(file) if nil != err{ return err } bucket.Put(filename, data, "image/jpeg", s3.PublicRead, s3.Options{}) Postgresql and golang
|
|