Go Web App

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
"fmt"
"log"
"net/http"
"os"
)

func printUsage() {
	fmt.Println(os.Args[0] + ` - Serve a directory via HTTP

URL should include protocol IP or hostname and port separated by colon.

Usage:
  ` + os.Args[0] + ` <listenUrl> <directory>

Example:
  ` + os.Args[0] + ` localhost:8080 .
  ` + os.Args[0] + ` 0.0.0.0:9999 /home/nanodano
`)
}

func checkArgs() (string, string) {
	if len(os.Args) != 3 {
		printUsage()
		os.Exit(1)
	}
	return os.Args[1], os.Args[2]
}

func main() {
	listenUrl, directoryPath := checkArgs()
	err := http.ListenAndServe(listenUrl, http.FileServer(http.Dir(directoryPath)))
	if err != nil {
		log.Fatal("Error running server. ", err)
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
	"fmt"
	"net/http"
	"log"
)

func indexHandler(writer http.ResponseWriter, request *http.Request) {
	// Write the contents of the response body to the writer interface
	// Request object contains information about and from the client
	fmt.Fprintf(writer, "You requested: " + request.URL.Path)
}

func main() {
	http.HandleFunc("/", indexHandler)
	err := http.ListenAndServe("localhost:8080", nil)
	if err != nil {
		log.Fatal("Error creating server. ", err)
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
	"fmt"
	"log"
	"net/http"
)

func indexHandler(writer http.ResponseWriter, request *http.Request) {
	fmt.Fprintf(writer, "You requested: "+request.URL.Path)
}

func main() {
	http.HandleFunc("/", indexHandler)
	err := http.ListenAndServeTLS(
		"localhost:8181",
		"cert.pem",
		"privateKey.pem",
		nil,
	)
	if err != nil {
		log.Fatal("Error creating server. ", err)
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import (
	"fmt"
	"net/http"
	"log"
	"time"
)

func indexHandler(writer http.ResponseWriter, request *http.Request) {
	secureSessionCookie := http.Cookie {
		Name: "SessionID",
		Value: "<secure32ByteToken>",
		Domain: "yourdomain.com",
		Path: "/",
		Expires: time.Now().Add(60 * time.Minute),
		HttpOnly: true, // Prevents JavaScript from accessing
		Secure: true, // Requires HTTPS
	}

	// Write cookie header to response
	http.SetCookie(writer, &secureSessionCookie)
	fmt.Fprintln(writer, "Cookie has been set.")
}



func main() {
	http.HandleFunc("/", indexHandler)
	err := http.ListenAndServe("localhost:8080", nil)
	if err != nil {
		log.Fatal("Error creating server. ", err)
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"html"
)

func main() {
	rawString := `<script>alert("Test");</script>`
	safeString := html.EscapeString(rawString)

	fmt.Println("Unescaped: " + rawString)
	fmt.Println("Escaped: " + safeString)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/urfave/negroni"
)

// Custom middleware handler logs user agent
func customMiddlewareHandler(rw http.ResponseWriter,
	r *http.Request,
	next http.HandlerFunc,
) {
	log.Println("Incoming request: " + r.URL.Path)
	log.Println("User agent: " + r.UserAgent())

	next(rw, r) // Pass on to next middleware handler
}

// Return response to client
func indexHandler(writer http.ResponseWriter, request *http.Request) {
	fmt.Fprintf(writer, "You requested: "+request.URL.Path)
}

func main() {
	multiplexer := http.NewServeMux()
	multiplexer.HandleFunc("/", indexHandler)

	negroniHandler := negroni.New()
	negroniHandler.Use(negroni.HandlerFunc(customMiddlewareHandler))
	negroniHandler.UseHandler(multiplexer)

	http.ListenAndServe("localhost:3000", negroniHandler)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
	"fmt"
	"net/http"

	"github.com/urfave/negroni"
)

// Custom middleware handler logs user agent
func addSecureHeaders(rw http.ResponseWriter, r *http.Request,
	next http.HandlerFunc) {
	rw.Header().Add("Content-Security-Policy", "default-src 'self'")
	rw.Header().Add("X-Frame-Options", "SAMEORIGIN")
	rw.Header().Add("X-XSS-Protection", "1; mode=block")
	rw.Header().Add("Strict-Transport-Security", "max-age=10000, includeSubdomains; preload")
	rw.Header().Add("X-Content-Type-Options", "nosniff")

	next(rw, r) // Pass on to next middleware handler
}

// Return response to client
func indexHandler(writer http.ResponseWriter, request *http.Request) {
	fmt.Fprintf(writer, "You requested: "+request.URL.Path)
}

func main() {
	multiplexer := http.NewServeMux()
	multiplexer.HandleFunc("/", indexHandler)

	negroniHandler := negroni.New()

	// Set up as many middleware functions as you need, in order
	negroniHandler.Use(negroni.HandlerFunc(addSecureHeaders))
	negroniHandler.Use(negroni.NewLogger())
	negroniHandler.UseHandler(multiplexer)

	http.ListenAndServe("localhost:3000", negroniHandler)
}
1
negroniHandler.Use(negroni.NewStatic(http.Dir("/path/to/static/files")))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	// Make basic HTTP GET request
	response, err := http.Get("http://www.example.com")
	if err != nil {
		log.Fatal("Error fetching URL. ", err)
	}

	// Read body from response
	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if err != nil {
		log.Fatal("Error reading response. ", err)
	}

	fmt.Printf("%s\n", body)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
	"crypto/tls"
	"log"
	"net/http"
)

func main() {
	// Load cert
	cert, err := tls.LoadX509KeyPair("cert.pem", "privKey.pem")
	if err != nil {
		log.Fatal(err)
	}

	// Configure TLS client
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	tlsConfig.BuildNameToCertificate()
	transport := &http.Transport{TLSClientConfig: tlsConfig}
	client := &http.Client{Transport: transport}

	// Use client to make request.
	// Ignoring response, just verifying connection accepted.
	_, err = client.Get("https://example.com")
	if err != nil {
		log.Println("Error making request. ", err)
	}
}
1
os.Setenv("HTTP_PROXY", "proxyIp:proxyPort")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

func main() {
	proxyUrlString := "http://<proxyIp>:<proxyPort>"
	proxyUrl, err := url.Parse(proxyUrlString)
	if err != nil {
		log.Fatal("Error parsing URL. ", err)
	}

	// Set up a custom HTTP transport for client
	customTransport := &http.Transport{
		Proxy: http.ProxyURL(proxyUrl),
	}
	httpClient := &http.Client{
		Transport: customTransport,
		Timeout:   time.Second * 5,
	}

	// Make request
	response, err := httpClient.Get("http://www.example.com")
	if err != nil {
		log.Fatal("Error making GET request. ", err)
	}
	defer response.Body.Close()

	// Read and print response from server
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal("Error reading body of response. ", err)
	}
	log.Println(string(body))

}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

// The Tor proxy server must already be running and listening
func main() {
	targetUrl := "https://check.torproject.org"
	torProxy := "socks5://localhost:9050" // 9150 w/ Tor Browser

	// Parse Tor proxy URL string to a URL type
	torProxyUrl, err := url.Parse(torProxy)
	if err != nil {
		log.Fatal("Error parsing Tor proxy URL:", torProxy, ". ", err)
	}

	// Set up a custom HTTP transport for the client
	torTransport := &http.Transport{Proxy: http.ProxyURL(torProxyUrl)}
	client := &http.Client{
		Transport: torTransport,
		Timeout:   time.Second * 5,
	}

	// Make request
	response, err := client.Get(targetUrl)
	if err != nil {
		log.Fatal("Error making GET request. ", err)
	}
	defer response.Body.Close()

	// Read response
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal("Error reading body of response. ", err)
	}
	log.Println(string(body))
}

相关内容