# Go Web HW
###### tags `Go`
---
## install package
1. install go binary
1-1 in windows
1-2 in linux
2. install go with gvm (go version management)(option)
[gvm](https://github.com/moovweb/gvm)
## install editor / ide
choose below one
1. [vim](https://www.vim.org/) with plugin [vim-go](https://github.com/fatih/vim-go)
2. [vscode](https://code.visualstudio.com/) with plugin [Go](https://marketplace.visualstudio.com/items?itemName=golang.go)
3. [goland](https://www.jetbrains.com/go/) or [intellij](https://www.jetbrains.com/idea/) with plugin [go](https://plugins.jetbrains.com/plugin/9568-go)
---
## get started
1. run hello
[Get started with Go](https://go.dev/doc/tutorial/getting-started)
2. run module
[Create a Go module](https://go.dev/doc/tutorial/create-module)
3. leetcode
[Two Sum](https://leetcode.com/problems/two-sum/)
[Majority Element](https://leetcode.com/problems/majority-element/)
---
## web
1. web server
```go
// main.go
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"strings"
"time"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
n := rand.Intn(5)
time.Sleep(time.Duration(n) * time.Second)
fmt.Fprintf(w, "Hello %d\n", n)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hello", sayhelloName)
server := &http.Server{
Addr: ":9090",
Handler: mux,
}
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
```
1-1. hello
1-2. random sleep (0~5 second) then show hello
2. with parameter
2-1. url change ie. /sayHello
2-2. url with parameter ie. /sayHello?user=Jo
3. pass parameter by form
```html
<!-- login.gtlp -->
<html>
<head>
<title></title>
</head>
<body>
<form action="/login" method="post">
使用者名稱:<input type="text" name="username">
密碼:<input type="password" name="password">
<input type="submit" value="登入">
</form>
</body>
</html>
```
```go!
// main.go
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello astaxie!")
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
r.ParseForm()
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
log.Println(t.Execute(w, nil))
} else {
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
}
}
func main() {
http.HandleFunc("/", sayhelloName)
http.HandleFunc("/login", login)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
```
3-1. show username and password when these no empty
3-2. setup a username and password when these are right to show login successful
3-3. upload file
3-4. download file
3-5. access token(hiden tag)
4. static page
```htmlembedded!
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous"
/>
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"
></script>
</body>
</html>
```
4-1 use this static html run with go web server
---
## sql
1. sqlite
1-1 install [sqlite](https://www.sqlite.org/index.html)
1-2 create db, table and insert/query/update/delete data by sqlite client tool
1-3 insert/query/update/delete data by sql driver (eg. [go-sqlite3](https://github.com/mattn/go-sqlite3))
1-4 insert/query/update/delete data by orm (eg. [gorm](https://github.com/go-gorm/gorm), [beego](https://github.com/beego/beego) )
1-5 insert/query/update/delete data by gui tool (eg. [DBeaver](https://dbeaver.io/), [DB Browser](https://sqlitebrowser.org/), [SQLiteStudio](https://www.sqlitestudio.pl/))
2. mysql / mariadb
2-1 intall [mysql](https://www.mysql.com/) / mariadb
2-2 create db, table and insert/query/update/delete data by mysql client tool
2-3 insert/query/update/delete data by sql driver (eg. [mysql](https://github.com/go-sql-driver/mysql))
2-4 insert/query/update/delete data by by orm (eg. [gorm](https://github.com/go-gorm/gorm), [beego](https://github.com/beego/beego) )
2-5 insert/query/update/delete data by gui tool (eg. [DBeaver](https://dbeaver.io/), [phpMyAdmin](https://www.phpmyadmin.net/), [MySQL Workbench](https://dev.mysql.com/downloads/workbench/))
3. postgresql
3-1 install [postgresql](https://www.postgresql.org/)
3-2 create db, table and insert/query/update/delete data by postgres client tool
3-3 insert/query/update/delete data by sql driver (eg. [pg](https://github.com/lib/pq))
3-4 insert/query/update/delete data by by orm (eg. [gorm](https://github.com/go-gorm/gorm), [beego](https://github.com/beego/beego) )
3-5 insert/query/update/delete data by gui tool (eg. [DBeaver](https://dbeaver.io/), [pgAdmin](https://www.pgadmin.org/))
---
## no sql
1. redis
1-1 install [redis](https://redis.io/)
1-2 get/set/delete data by redis-cli
1-3 get/set/delete data by gui tool (eg.[RedisDesktopManager](https://github.com/RedisInsight/RedisDesktopManager), [AnotherRedisDesktopManager](https://github.com/qishibo/AnotherRedisDesktopManager/))
1-4. get/set/delete data by lib ([go-redis](https://github.com/redis/go-redis), [redigo](https://github.com/gomodule/redigo), [radix](https://github.com/mediocregopher/radix))
2. mongodb
2-1 install [mongodb](https://www.mongodb.com/)
2-2 create/read/update/delete data by mongodb client
2-3 create/read/update/delete data by mongodb gui [MongoDB Compass](https://www.mongodb.com/try/download/compass), (Robomongo -> Robo 3T -> [Studio 3T](https://studio3t.com/))
2-4 get/set/delete data by lib [mongo-go-driver](https://github.com/mongodb/mongo-go-driver), [mgo]()
---
## cookie and session
1. cookie
1-1 show cookie file and data in localhost (chrome/edge/firefox/safari)
1-2 set/get/del cookie
2. session
2-1 set/get/del cookie in memory
2-2 set/get/del cookie with sqlite
2-3 set/get/del cookie with mysql
2-4 set/get/del cookie with postgresql
2-5 set/get/del cookie with redis
---
## text
1. xml
1-1 read xml to show data
1-2 data write to xml
2. json
2-1 read json to show data
2-2 data write to json
3. regexp
3-1 ipv4 regex (dec, hex)
3-2 "lang:shell,c,c++,java" by group
```go!
package main
import (
"fmt"
"regexp"
)
func main() {
var re = regexp.MustCompile(`(?mi)(?:lang:)?\b(([+-]|[a-z])+)(,|\b)`)
// var re = regexp.MustCompile(`(?mi)\b([a-zA-Z+]+)(?!\:)+,?\b`)
var str = `lang:shell,c,c++,c--,java`
for i, match := range re.FindAllStringSubmatch(str, -1) {
fmt.Println(match, "found at index", i)
fmt.Println(match[1])
}
submatchall := re.FindAllSubmatch([]byte(str), -1)
fmt.Println("FindSubmatch", submatchall)
for _, v := range submatchall {
fmt.Println(string(v[1]))
}
}
```
4. template
4-1 create html by template
4-2 create json by template
4-3 create yaml by template
5. file
5-1 read and write file
6. string
---
## web serice
---
1. socket
1-1 send and recieve message by local socket file
1-2 send and recieve message by ipv4
1-2 send and recieve message by ipv6
2. websocket
3. restful
3-1 crud api with database mysql
3-2 crud api with database postgrq
3-3 crud api with database sqlite
4. rpc
4-1 rpc by tcp
4-2 rpc by http
4-3 rpc by json
5. grpc
5-1 grpc
---
## security
1. DVWA / Damn Vulnerable Web Application
1-1 install
1-2 sql injection
1-3 csrf
1-4 xss
2.CSRF
2-1 gorilla/csrf html example
2-2 gorilla/csrf api / backend example
3. XSS
3-1 html exmple
4. SQL injection
4-1 mysql example
4-2 postgre example
5. Command injection
5-1 example
---
## ref
- [build-web-application-with-golang](https://github.com/astaxie/build-web-application-with-golang/tree/master)*
- [使用 Golang 打造 Web 應用程式](https://willh.gitbook.io/build-web-application-with-golang-zhtw/)*
- [Tutorials](https://go.dev/doc/tutorial/)
- [Go 语言高级编程](https://chai2010.cn/advanced-go-programming-book/index.html)
- [How To Code in Go](https://www.digitalocean.com/community/tutorial-series/how-to-code-in-go)
- [Go 语言实战开发 - 中文入门教学](https://www.youtube.com/playlist?list=PLliocbKHJNwsUOfWKxrDU6adIQ4QiI-2g)