Skip to content

Instantly share code, notes, and snippets.

@cemeng
Created February 20, 2018 22:39
Show Gist options
  • Save cemeng/4b9141d14b9209c2cbddb24126633783 to your computer and use it in GitHub Desktop.
Save cemeng/4b9141d14b9209c2cbddb24126633783 to your computer and use it in GitHub Desktop.
Golang Study Notes
My Golang study note
@cemeng
Copy link
Author

cemeng commented Feb 20, 2018

21/2 - Focus on today is error handling in Go

Back to Golang learning - learning about error handling in Go:
https://blog.golang.org/error-handling-and-go

Sharing with the group:

  • Afaik, there is no repl - use Golang playground
  • Error handling in Go:

https://play.golang.org/p/Mv7FADkEz9V
https://blog.golang.org/error-handling-and-go

My takeaway:

  • I kinda like that the a method that raises an error need to do that explicitly, that is they need to return the error as part of the function return. In Go - by design, you need to explicitly check for errors - different from other languages that throw exception and "sometimes" catching them.
  • The need to explicitly handle error will make your code verbose - in that blog post, it proposes a way to avoid that by introducing an error handler -> but I don't really get it.
  • You can use fmt.Errorf to format string according to Printf rules and returns it as error for example:
    return 0, fmt.Errorf("math: %g", f)
  • Create your own error type by "implementing" error interface - I am not too familiar with interface yet, so need to read up more about it. But at high level, it just means create a type that has an "Error()" method.
    Here is an example:
type NegativeSqrtError float64

func (f NegativeSqrtError) Error() string {
    return fmt.Sprintf("math: square root of negative number %g", float64(f))
}

Further questions:

  • How is interface works in Go?
  • What is a type in Go? And how is it different to structure?

@cemeng
Copy link
Author

cemeng commented Feb 22, 2018

22/2

dep -> dependency management in go https://github.com/golang/dep - does blue team use this?

started following gowebexamples.com
unable to start web server on port 80 - wondering why, using log.Fatal helps
log.Fatal(http.ListenAndServe(":80", nil))

Middleware

TIL: you can pass in a function as a param to a function.
A function has a type - the type is determined by the function signature.

func logging(f http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.URL.Path)
		f(w, r)
	}
}

https://gowebexamples.com/basic-middleware/

Basically middleware is just a function that takes http.HandlerFunc and return http.HandlerFunc

Advanced Middleware

create a middleware type
type Middleware func(http.HandlerFunc) http.HandlerFunc
and you can chain em - you need to create your own Chain method urgh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment