Jump to content

Server-Side Scripting/Requests/Go

From Wikiversity

lesson3.go

[edit | edit source]
// Converts a Fahrenheit temperature to Celsius using a GET request and
// converts a Celsius temperature to Fahrenheit using a POST request.
//
// References:
//  https://www.mathsisfun.com/temperature-conversion.html
//  https://golang.org/doc/
//  https://golangcode.com/get-a-url-parameter-from-a-request/
//  https://gowebexamples.com/forms/

package routes

import (
	"fmt"
    "net/http"
    "html/template"
    "path/filepath"
	"strconv"
)

func Lesson3(response http.ResponseWriter, request *http.Request) {
	response.Header().Set("Content-Type", "text/html; charset=utf-8")

	type Data struct {
		Fahrenheit  string
		Celsius		string
	}
	
	fahrenheit := ""
	celsius := ""

	if request.Method == "GET" {
        fahrenheit = processGetRequest(request)
    } else if request.Method == "POST" {
        celsius = processPostRequest(request)
    }

	data := Data{fahrenheit, celsius}
	path := filepath.Join("templates", "lesson3.html")
	parsed, _ := template.ParseFiles(path)
	parsed.Execute(response, data)
}

func processGetRequest(request *http.Request) string {
    result := ""

    parameters := request.URL.Query()["fahrenheit"]
    if len(parameters) > 0 {
        fahrenheit, err := strconv.ParseFloat(parameters[0], 32)
        if err == nil {
            celsius := (fahrenheit - 32) * 5.0 / 9.0
            result += fmt.Sprintf("%f° Fahrenheit is %f° Celsius", 
                fahrenheit, celsius)
        }
	}

    return result
}

func processPostRequest(request *http.Request) string {
    result := ""
    value := request.FormValue("celsius")
    celsius, err := strconv.ParseFloat(value, 32)
    if err == nil {
        fahrenheit := celsius * 9.0 / 5.0 + 32
        result += fmt.Sprintf("%f° Celsius is %f° Fahrenheit", 
            celsius, fahrenheit)
    }

    return result;
}

lesson3.html

[edit | edit source]
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Lesson 3</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        p {
            min-height: 1em;
        }
    </style>
</head>
  <body>
    <form method="GET">
        <p>
            <label for="fahrenheit">Enter Fahrenheit temperature:</label>
            <input type="text" id="fahrenheit" name="fahrenheit">
            <input type="submit" value="Submit">
        </p>
        <p>
            <output>{{.Fahrenheit}}</output>
        </p>
    </form>
    <form method="POST">
        <p>
            <label for="celsius">Enter Celsius temperature:</label>
            <input type="text" id="celsius" name="celsius">
            <input type="submit" value="Submit">
        </p>
        <p>
            <output>{{.Celsius}}</output>
        </p>
    </form>
</body>
</html>

Try It

[edit | edit source]

See Server-Side Scripting/Routes and Templates/Go to create a test environment.