Http web frame with Go Programming Language

JWeb

  • Http web frame with Go Programming Language

Install

go get -u github.com/jiang1223684476/jweb

How to use?

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/jiang1223684476/jweb/app"
	"html/template"
	"io/ioutil"

	"log"
	"net/http"
	"path"
)

func main() {
	// replace default max request size
	app.MaxRequestSize = 1024 * 1024
	// replace default template directory
	app.TemplateDirectory = "views"
	// replace default static directory
	app.StaticDirectory = "static"

	// replace default global handler
	app.GlobalHandler = func(c *app.Context) {
	}
	// replace default response handler
	app.ResponseHandler = func(c *app.Context) {
		c.Status = http.StatusOK
		c.StatusText = http.StatusText(http.StatusOK)
		c.ContentType = app.ContentText
	}
	// replace default not found handler
	app.NotFoundHandler = func(c *app.Context) {
		c.Status = http.StatusNotFound
		c.StatusText = http.StatusText(http.StatusNotFound)
		c.ContentType = app.ContentHTML
		c.Data = http.StatusText(http.StatusNotFound)
	}
	// replace default json serialization handler
	app.JsonHandler = func(data interface{}) string {
		marshal, err := json.Marshal(data)
		if err != nil {
			log.Println(err)
			return ""
		}

		return string(marshal)
	}
	// replace default html rendering handler
	app.HtmlHandler = func(templateName string, data interface{}) string {
		// the file name extension
		extension := ".html"

		// get template file names
		var templateFileNames []string
		dir, err := ioutil.ReadDir(app.TemplateDirectory)
		if err != nil {
			log.Println(err)
			return ""
		}
		for _, v := range dir {
			fileName := v.Name()
			// check extension
			ext := path.Ext(fileName)
			if ext == extension {
				templateFileNames = append(templateFileNames, fmt.Sprintf("%s/%s", app.TemplateDirectory, fileName))
			}
		}

		// parse template file name
		t := template.New(fmt.Sprintf("%s%s", templateName, extension))
		// custom func
		t.Funcs(template.FuncMap{})
		// parse files
		_, err = t.ParseFiles(templateFileNames...)
		if err != nil {
			log.Println(err)
			return ""
		}
		// get template parse data
		buffer := new(bytes.Buffer)
		err = t.Execute(buffer, data)
		if err != nil {
			log.Println(err)
			return ""
		}

		return buffer.String()
	}

	// request GET
	app.Get("/", func(c *app.Context) {
		// app.Html rendering data to html
		c.Data = app.Html(c, "index", app.Map{
			// Path request path
			"path": c.Path,
			// Method request path
			"method": c.Method,
			// Query request query value
			// http://127.0.0.1:8080/?id=1
			"id": c.Query("id", "0"),
		})
	})
	// Dynamic routing using regexp
	// for example /user/id:\d+
	// http://127.0.0.1:8080/user/1
	app.Get(`/user/id:\d+`, func(c *app.Context) {
		// Cookie get cookie
		cookieName := c.Cookie("cookieName", "")
		if cookieName == "" {
			// SetCookie set response cookie
			app.SetCookie(c, app.Cookie{Name: "cookieName", Value: "miku", MaxAge: 60 * 60 * 24})
		} else {
			log.Println(cookieName)
		}
		// RemoveCookie remove cookie by name
		app.RemoveCookie(c, "cookieName")

		// Session get session
		sessionName := c.Session("sessionName", "")
		if sessionName == "" {
			// SetSession set response session
			app.SetSession(c, "sessionName", "haku")
		} else {
			log.Println(sessionName)
		}
		// RemoveSession remove session by name
		app.RemoveSession(c, "sessionName")

		// SetHeader set response header
		app.SetHeader(c, app.Header{
			Name:  "Server",
			Value: "Test",
		})

		// Redirect set redirect header
		//app.Redirect(c, "/")

		// set specify response Content-Type
		//c.ContentType = app.ContentJSON

		// app.Json serialization data to json
		c.Data = app.Json(c, app.Map{
			"path":   c.Path,
			"method": c.Method,
			// Params get value form dynamic routing
			"id": app.Params(c, "id", "0"),
			// get request specify header value
			"User-Agent": c.Header("User-Agent", ""),
		})
	})
	// request POST
	app.Post("/", func(c *app.Context) {
		c.Data = app.Json(c, app.Map{
			"path":   c.Path,
			"method": c.Method,
			"id":     c.Form("id", "0"),
		})
	})
	// request PUT
	app.Put("/", func(c *app.Context) {
		c.Data = app.Json(c, app.Map{
			"path":   c.Path,
			"method": c.Method,
			"id":     c.Form("id", "0"),
		})
	})
	// request DELETE
	app.Delete("/", func(c *app.Context) {
		c.Data = app.Json(c, app.Map{
			"path":   c.Path,
			"method": c.Method,
			"id":     c.Form("id", "0"),
		})
	})

	address := "127.0.0.1:8080"
	// run applications in specify address
	app.Run(address)
}

Have fun!

Similar Resources

A stack oriented esoteric programming language inspired by poetry and forth

paperStack A stack oriented esoteric programming language inspired by poetry and forth What is paperStack A stack oriented language An esoteric progra

Nov 14, 2021

Oak is an expressive, dynamically typed programming language

Oak 🌳 Oak is an expressive, dynamically typed programming language. It takes the best parts of my experience with Ink, and adds what I missed and rem

Dec 30, 2022

Besten programming language

Besten What holds this repository? Besten Lexer Besten Parser Besten Interpreter Besten Module Loader Besten Lexer Located in ./internal/lexer A set o

Jun 13, 2022

🎅 A programming language for Advent of Code.

🎅 Adventlang My blog post: Designing a Programming Language for Advent of Code A strongly typed but highly dynamic programming language interpreter w

Dec 28, 2022

An experimental programming language.

crank-lang An experimental & interpreted programming language written in Go. Features C like syntax Written in Golang Interpreted Statically Typed Dis

Dec 6, 2021

Gec is a minimal stack-based programming language

Gec is a minimal stack-based programming language

Sep 18, 2022

A Simple Bank Web Service implemented in Go, HTTP & GRPC, PostgreSQL, Docker, Kubernetes, GitHub Actions CI

simple-bank Based on this Backend Master Class by TECH SCHOOL: https://youtube.com/playlist?list=PLy_6D98if3ULEtXtNSY_2qN21VCKgoQAE Requirements Insta

Dec 9, 2021

Functional programming library for Go including a lazy list implementation and some of the most usual functions.

functional A functional programming library including a lazy list implementation and some of the most usual functions. import FP "github.com/tcard/fun

May 21, 2022

Flow-based and dataflow programming library for Go (golang)

Flow-based and dataflow programming library for Go (golang)

GoFlow - Dataflow and Flow-based programming library for Go (golang) Status of this branch (WIP) Warning: you are currently on v1 branch of GoFlow. v1

Dec 30, 2022
Related tags
Jan 4, 2022
Unit tests generator for Go programming language
Unit tests generator for Go programming language

GoUnit GoUnit is a commandline tool that generates tests stubs based on source function or method signature. There are plugins for Vim Emacs Atom Subl

Jan 1, 2023
FreeSWITCH Event Socket library for the Go programming language.

eventsocket FreeSWITCH Event Socket library for the Go programming language. It supports both inbound and outbound event socket connections, acting ei

Dec 11, 2022
Simple interface to libmagic for Go Programming Language

File Magic in Go Introduction Provides simple interface to libmagic for Go Programming Language. Table of Contents Contributing Versioning Author Copy

Dec 22, 2021
The Gorilla Programming Language
The Gorilla Programming Language

Gorilla Programming Language Gorilla is a tiny, dynamically typed, multi-engine programming language It has flexible syntax, a compiler, as well as an

Apr 16, 2022
Elastic is an Elasticsearch client for the Go programming language.

Elastic is an Elasticsearch client for the Go programming language.

Jan 9, 2023
👩🏼‍💻A simple compiled programming language
👩🏼‍💻A simple compiled programming language

The language is written in Go and the target language is C. The built-in library is written in C too

Nov 29, 2022
Lithia is an experimental functional programming language with an implicit but strong and dynamic type system.

Lithia is an experimental functional programming language with an implicit but strong and dynamic type system. Lithia is designed around a few core concepts in mind all language features contribute to.

Dec 24, 2022
accessor methods generator for Go programming language

accessory accessory is an accessor generator for Go programming language. What is accessory? Accessory is a tool that generates accessor methods from

Nov 15, 2022
A modern programming language written in Golang.

MangoScript A modern programming language written in Golang. Here is what I want MangoScript to look like: struct Rectangle { width: number he

Nov 12, 2021