Add http golang

This commit is contained in:
Wilfried OLLIVIER 2022-03-24 11:07:48 +01:00
parent d40d70ddce
commit bf47895f40
2 changed files with 68 additions and 0 deletions

View File

@ -5,6 +5,7 @@
- [Dev](./dev/main.md)
- [Golang](./dev/golang/main.md)
- [http](./dev/golang/http.md)
- [Packages](./dev/golang/packages.md)
- [Testing](./dev/golang/testing.md)
- [Elixir](./dev/elixir/main.md)

67
src/dev/golang/http.md Normal file
View File

@ -0,0 +1,67 @@
# http package stuff
## HTTP Status Code
Do not use number directly.
Don't do this
```golang
w.WriteHeader(404)
```
Do this
```golang
w.WriteHeader(http.StatusNotFound)
```
## Error message
```golang
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
```
## Flusher
A [Flusher](https://pkg.go.dev/net/http#Flusher) can be used to allow an HTTP handler to flush buffered data to the client.
```golang
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ended := make(chan bool)
f, flushable := w.(http.Flusher)
if flushable {
go func() {
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ticker.C:
fmt.Println("debug")
io.WriteString(w, "#")
f.Flush()
case <-ended:
return
case <-r.Context().Done():
return
}
}
}()
}
time.Sleep(5 * time.Second)
ended <- true
w.Write([]byte("ok"))
})
http.ListenAndServe(":8080", nil)
}
```