zmiana struktury - usuniecie z tutorialow rzeczy

This commit is contained in:
pawlaczyk 2019-01-06 00:24:09 +01:00
parent d023900d73
commit f071bc9513
51 changed files with 13 additions and 5084 deletions

View File

@ -8,10 +8,12 @@ import (
) )
// create your own document // create your own document
type dummyDocument struct { type cardDocument struct {
couchdb.Document couchdb.Document
Foo string `json:"foo"` ID int `json:"id" binding:"required"`
Beep string `json:"beep"` isQuestion bool `json:"typ"` //True karta pytanie, False karta odpowiedź
Blank int `json:"puste" binding:"required"` //ile kart odpowiedzi na pytanie
Text string `json:"tekst" binding:"required"` // podłoga to luka
} }
func connectCouchdb(url_couchdb string) { func connectCouchdb(url_couchdb string) {
@ -50,7 +52,7 @@ func main() {
// use your new "dummy" database and create a document // use your new "dummy" database and create a document
db := client.Use("dummy") db := client.Use("dummy")
doc := &dummyDocument{ doc := &cardDocument{
Foo: "bar", Foo: "bar",
Beep: "bopp", Beep: "bopp",
} }

BIN
backend/backend/main.exe Normal file

Binary file not shown.

View File

@ -56,6 +56,7 @@ func main() {
api.GET("/jokes", JokeHandler) api.GET("/jokes", JokeHandler)
api.POST("/jokes/like/:jokeID", LikeJoke) api.POST("/jokes/like/:jokeID", LikeJoke)
api.POST("/cards", getAllCards) api.POST("/cards", getAllCards)
api.GET("/getAllCards", getAllCards)
// Start and run the server // Start and run the server
router.Run(":3000") router.Run(":3000")

View File

@ -3,10 +3,10 @@ package main
// Structura karty // Structura karty
type Card struct { type Card struct {
ID int `json:"id" binding:"required"` ID int `json:"id" binding:"required"`
Type int `json:"typ"` //0 karta pytanie, 1 karta odpowiedź isQuestion int `json:"typ"` //0 karta pytanie, 1 karta odpowiedź
Blank int `json:"puste" binding:"required"` //ile kart odpowiedzi na pytanie Blank int `json:"puste" binding:"required"` //ile kart odpowiedzi na pytanie
Text string `json:"tekst" binding:"required"` // podłoga to luka Text string `json:"tekst" binding:"required"` // podłoga to luka
} }
// Lista card // Lista card

BIN
backend/backend/views.exe Normal file

Binary file not shown.

View File

@ -8,10 +8,8 @@ import (
) )
func getAllCards(c *gin.Context) { func getAllCards(c *gin.Context) {
fmt.Println("Pobieranie wszystkich kart z bazy - pytań i odpowiedzi") c.Header("Content-Type", "application/json")
fmt.Println("Długość listy: ", len(cards)) c.JSON(http.StatusOK, cards)
c.JSON(http.StatusOK, &cards)
} }
func addNewCard() { func addNewCard() {

View File

@ -1,11 +0,0 @@
1. Adres Bazy
http://127.0.0.1:5984/
2. Wyszuanie wszystkich baz przez curl
curl -X GET http://127.0.0.1:5984/_all_dbs
3. Futon - webowy klient
http://localhost:5984/_utils/
4. Baza
go_test

View File

@ -1,68 +0,0 @@
package main
import (
"fmt"
"net/url"
"github.com/zemirco/couchdb"
)
// create your own document
type dummyDocument struct {
couchdb.Document
Foo string `json:"foo"`
Beep string `json:"beep"`
}
// start
func main() {
u, err := url.Parse("http://127.0.0.1:5984/")
if err != nil {
panic(err)
}
// create a new client
client, err := couchdb.NewClient(u)
if err != nil {
panic(err)
}
// get some information about your CouchDB
info, err := client.Info()
if err != nil {
panic(err)
}
fmt.Println(info)
// // create a database
// if _, err = client.Create("dummy"); err != nil {
// panic(err)
// }
// use your new "dummy" database and create a document
db := client.Use("dummy")
doc := &dummyDocument{
Foo: "bar",
Beep: "bopp",
}
result, err := db.Post(doc)
if err != nil {
panic(err)
}
// get id and current revision.
if err := db.Get(doc, result.ID); err != nil {
panic(err)
}
// delete document
if _, err = db.Delete(doc); err != nil {
panic(err)
}
// and finally delete the database
if _, err = client.Delete("dummy"); err != nil {
panic(err)
}
}

View File

@ -1,26 +0,0 @@
//cwiczenie 1 str 23
package main
import (
"fmt"
"os"
"strings"
"time"
)
func main() {
start1 := time.Now()
for i := 0; i < len(os.Args); i++ {
fmt.Println(i, " ", os.Args[i])
}
end1 := time.Now()
fmt.Println("Koniec1", end1.Sub(start1))
start2 := time.Now()
fmt.Println(strings.Join(os.Args, " "))
end2 := time.Now()
fmt.Println("Koniec2", end2.Sub(start2))
}

View File

@ -1,27 +0,0 @@
// wyswietlanie tekstu kazdej linii która pojawiła się na IO
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
// fmt.Println(counts)
}
// //UWAGA: ignorowowanie potencjalnych błędów z funkcji input.Err()
for line, n := range counts {
// z jakiegos powodu
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
// fmt.Printf("%d", n)
}
}
}

View File

@ -1,16 +0,0 @@
//Echo1 wyświetla swoje argumenty wiersza poleceń
package main
import(
"fmt"
"os"
)
func main(){
var s, sep string
for i :=1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = "\n"
}
fmt.Println(s)
}

View File

@ -1,20 +0,0 @@
//Echo2 wyświetla swoje argumenty wiersza poleceń
package main
import (
"fmt"
"os"
)
func main() {
s, sep := "", ""
for _, arg := range os.Args { //taki foreach
fmt.Println(arg)
s += sep + arg //do zmiennej arg przypisana jest lista
sep = " "
}
fmt.Println(s)
// fmt.Println(os.Args)
// fmt.Println(strings.Join(os.Args, " "))
}

View File

@ -1,22 +0,0 @@
package main
import (
"fmt"
"time"
)
func compute(value int) {
for i := 0; i < value; i++ {
time.Sleep(time.Second)
fmt.Println(i)
}
}
func main() {
fmt.Println("Concurrency With GoRoutines")
go compute(5) //asynchroniczne wywolania goutis routine
go compute(5)
fmt.Scanln() //zeby petla glowa(main) nie zakoncyl sie przed watkami
}

View File

@ -1,3 +0,0 @@
module github.com/pawlaczyk/go_jwt/client
require github.com/dgrijalva/jwt-go v3.2.0+incompatible

View File

@ -1,2 +0,0 @@
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=

View File

@ -1,78 +0,0 @@
package main
// go get github.com/dgrijalva/jwt-go
//cd client
// go mod init github.com/pawlaczyk/go-jwt/client
// [!] kropka przed nawiasami w token.Claims.(jwt.MapClaims)
//inaczej blad
//# command-line-arguments
// .\main.go:14:24: type jwt.MapClaims is not an expression
// .\main.go:14:24: cannot call non-function token.Claims (type jwt.Claims)
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go" //jwt jako alias do repo
)
var mySigningKey = []byte("mysupersecretphrase") //lepiej odczytywac to ze zmiennej srodowiskowej
// set My_JWT_TOKEN=mysupersecretphrase
//var mySigningKey = os.Get("My_JWT_TOKEN") dobra praktyka dla jakiegogolwkiek hasła, chroni przed upubliczniniem gdzies hasla na repo
func homePage(w http.ResponseWriter, r *http.Request) {
validToken, err := GenerateJWT()
if err != nil {
fmt.Fprintf(w, err.Error())
}
client := &http.Client{} //tworzy nowy Request
req, _ := http.NewRequest("GET", "http://localhost:9000/", nil)
req.Header.Set("Token", validToken) //dopisanie do hedera
res, err := client.Do(req)
if err != nil {
//jak cos nie tak
fmt.Fprintf(w, "Error: %s", err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Fprintf(w, err.Error())
}
fmt.Fprintf(w, string(body))
}
func handleRequests() {
http.HandleFunc("/", homePage)
log.Fatal(http.ListenAndServe(":9001", nil))
}
func GenerateJWT() (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims) //[!] Kropka przed nawiasami !!!!!!!!!
claims["authorized"] = true
claims["client"] = "Elliot Forbes"
claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
fmt.Println("Somethig get wrong %s", err.Error())
return "", err
}
return tokenString, nil
}
func main() {
fmt.Println("My Simple Client")
handleRequests()
}

View File

@ -1,3 +0,0 @@
module github.com/pawlaczyk/go-jwt/server
require github.com/dgrijalva/jwt-go v3.2.0+incompatible

View File

@ -1,2 +0,0 @@
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=

View File

@ -1,60 +0,0 @@
package main
import (
"fmt"
"log"
"net/http"
jwt "github.com/dgrijalva/jwt-go" //jwt jako alias do repo =~ import numpy as np ; jwt to takie np
)
var mySigningKey = []byte("mysupersecretphrase")
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Super Secret Information from Server")
fmt.Println("Endpoint Hit: homePage")
}
func isAuthorized(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
//modyfikacja funkcji homePage =~ jak dektorator w pythonie
//sprawdza czy jest prawidlowy JWTToken
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //[!] handleR nie samo handle
if r.Header["Token"] != nil {
//walidacja
//parsowanie naglowka z tokenem
// token *jwt.Token token to zmienna - [!] bez przecinka w func(token *jwt.Token) (interface{}, error)
// inaczej bład:
//# command-line-arguments
// .\main.go:26:55: undefined: token
// .\main.go:27:17: undefined: token
token, err := jwt.Parse(r.Header["Token"][0], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return mySigningKey, nil //nil zamias errora
})
if err != nil {
fmt.Fprintf(w, err.Error())
}
if token.Valid {
endpoint(w, r) //jak wszystko ok, to zwraca oryginalnego endpointa, przekazanego jako argument
}
} else {
//brak tokena
fmt.Fprintf(w, "Not Authorized")
}
})
}
func handleRequests() {
http.Handle("/", isAuthorized(homePage))
log.Fatal(http.ListenAndServe(":9000", nil))
}
func main() {
handleRequests()
}

View File

@ -1,58 +0,0 @@
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
Name string `json:"name"`
}
type User2 struct {
Name string `json:"name8"`
Name2 string `json:"name8"`
}
func main() {
fmt.Println("Go Mysql Tutorial")
db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/testdb")
if err != nil {
panic(err.Error())
}
fmt.Println("Succesfully Connected to MySQL database")
defer db.Close() //keep the connection open for the remainder of this function
// insert, err := db.Query("INSERT INTO users VALUES('ELLIOT3')")
insert, err := db.Query("INSERT INTO users2 VALUES('a1', 'b1')")
if err != nil {
panic(err.Error)
}
defer insert.Close()
fmt.Println("Succes Insert")
results, err := db.Query("SELECT * FROM users2")
if err != nil {
panic(err.Error())
}
for results.Next() {
var user2 User2
err = results.Scan(&user2.Name, &user2.Name2)
if err != nil {
panic(err.Error())
}
fmt.Println(user2.Name, user2.Name2)
}
fmt.Println(*results)
}

View File

@ -1,33 +0,0 @@
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func hangleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", helloWorld).Methods("GET")
myRouter.HandleFunc("/users", AllUsers).Methods("GET")
myRouter.HandleFunc("/user/{name}/{email}", NewUser).Methods("POST")
myRouter.HandleFunc("/user/{name}", DeleteUser).Methods("DELETE")
myRouter.HandleFunc("/user/{name}/{email}", UpdateUser).Methods("PUT")
log.Fatal(http.ListenAndServe(":8081", myRouter))
}
func main() {
fmt.Println("GO ORM Tutorial")
InitialMigration()
hangleRequests()
}

Binary file not shown.

View File

@ -1,109 +0,0 @@
// Użycie ORM dla bazy sqlite3
// w innych bazach na podobnej zasadzie
// operowanie raczej na metodach db niż modeli
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var db *gorm.DB
var err error
type User struct { // ~= models.py
gorm.Model //modeled somehow in the database
Name string
Email string
}
func InitialMigration() {
db, err = gorm.Open("sqlite3", "test.db")
if err != nil {
fmt.Println(err.Error())
panic("Failed to connect to database")
}
defer db.Close()
db.AutoMigrate(&User{}) //migracja modelu
}
func AllUsers(w http.ResponseWriter, r *http.Request) {
//widok
db, err = gorm.Open("sqlite3", "test.db")
if err != nil {
panic("Could not connect to the database")
}
defer db.Close()
var users []User //lista obiektow
db.Find(&users)
json.NewEncoder(w).Encode(users) //parsowanie lisy na jsona
}
func NewUser(w http.ResponseWriter, r *http.Request) {
//widok
db, err = gorm.Open("sqlite3", "test.db")
if err != nil {
panic("Could not connect to database")
}
defer db.Close()
// pobieranie danych z url'a
vars := mux.Vars(r) //wyłuskanie danych z obiekt request
name := vars["name"]
email := vars["email"]
// tworzenie obiektu Name - atrybut struktury, name wartosc zmiennej z url'a
db.Create(&User{Name: name, Email: email})
fmt.Fprintf(w, "New user successfully created")
}
func DeleteUser(w http.ResponseWriter, r *http.Request) {
//widok
db, err = gorm.Open("sqlite3", "test.db")
if err != nil {
panic("Could not connect to the database")
}
defer db.Close()
vars := mux.Vars(r) //wyłuskanie danych z obiekt request
name := vars["name"] //wyłuskanie danych ze zmiennej z url'a
//[!] USUWA WSZYSTKO db.Delete(&User{Name: name}) //USUWA WSZYSTKO [!]
var user User
//znajdz obiekt user, gdzie atrybut name jest równy zmiennej name
db.Where("name = ?", name).Find(&user)
//znajduje tylko jeden obiekt jesli dane sa identyczne w baze i tylko jeden usuwa
db.Delete(&user)
fmt.Fprintf(w, "DELETE User")
}
func UpdateUser(w http.ResponseWriter, r *http.Request) {
//widok
db, err = gorm.Open("sqlite3", "test.db")
if err != nil {
panic("Could not connect to the database")
}
defer db.Close()
vars := mux.Vars(r)
name := vars["name"]
email := vars["email"]
var user User
db.Where("name =?", name).Find(&user)
user.Email = email
db.Save(&user)
fmt.Fprintf(w, "UPDATE User")
}

View File

@ -1,21 +0,0 @@
package main
//stat -f%z person.xml nie dziala :<
// go get github.com/golang/protobuf
//[!] błąd [!] can't load package: package github.com/golang/protobuf: no Go files in C:\Users\dp\go\src\github.com\golang\protobuf
//go get github.com/golang/protobuf/proto
//https://github.com/golang/protobuf
//go get -u github.com/golang/protobuf/protoc-gen-go dziala
//The compiler plugin, protoc-gen-go, will be installed in $GOBIN,
//defaulting to $GOPATH/bin. It must be in your $PATH for the protocol compiler, protoc, to find it.
//protoc
// 'protoc' is not recognized as an internal or external command,
// operable program or batch file.
import "fmt"
func main() {
fmt.Println("Hello World")
}

View File

@ -1,4 +0,0 @@
{
"name": "Elliot",
"age": 24
}

View File

@ -1,8 +0,0 @@
syntax="proto3"
package main;
message Person {
string name =1;
int32 age = 2;
}

View File

@ -1,4 +0,0 @@
<person>
<name>Elliot</name>
<age>24</age>
</person>

View File

@ -1,45 +0,0 @@
<!doctype html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta charset="utf-8">
<title>Go wasm</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
if (!WebAssembly.instantiateStreaming) { // polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then((result) => {
mod = result.module;
inst = result.instance;
document.getElementById("runButton").disabled = false;
});
async function run() {
await go.run(inst);
inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance
}
</script>
<button onClick="run();" id="runButton" disabled>Run</button>
</body>
</html>

Binary file not shown.

View File

@ -1,13 +0,0 @@
package main
//[!] DOESNT WORK ON WINDOWS [!]
//backend dla frontu webowego
//GOARCH=wasm GOOS=js go build -o lib.wasm main.go
// go env
// set GOARCH=wasm
// set GOOS=js
// go build -o lib.wasm main.go
func main() {
println("Hello World")
}

View File

@ -1,20 +0,0 @@
//simple server
package main
import (
"flag"
"log"
"net/http"
)
var (
listen = flag.String("listen", ":8080", "listen address")
dir = flag.String("dir", ".", "directory to serve")
)
func main() {
flag.Parse()
log.Printf("Listening on %q...", *listen)
log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir))))
}

View File

@ -1,49 +0,0 @@
<!doctype html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta charset="utf-8">
<title>Go wasm</title>
</head>
<body>
<!--
Add the following polyfill for Microsoft Edge 17/18 support:
<script src="https://cdn.jsdelivr.net/npm/text-encoding@0.7.0/lib/encoding.min.js"></script>
(see https://caniuse.com/#feat=textencoder)
-->
<script src="wasm_exec.js"></script>
<script>
if (!WebAssembly.instantiateStreaming) { // polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then((result) => {
mod = result.module;
inst = result.instance;
document.getElementById("runButton").disabled = false;
}).catch((err) => {
console.error(err);
});
async function run() {
console.clear();
await go.run(inst);
inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance
}
</script>
<button onClick="run();" id="runButton" disabled>Run</button>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -1,48 +0,0 @@
//websocket zamiast rest api
// problem tylko z wysiwietlaniem danych z przegladarki
//Firefox:
//Zablokowano żądanie do zasobu innego pochodzenia: zasady „Same Origin Policy”
//nie pozwalają wczytywać zdalnych zasobów z „http://localhost:5000/socket.io/?EIO=3&transport=polling&t=MSKrtCr”
// (brakujący nagłówek CORS „Access-Control-Allow-Origin”).[Więcej informacji]
//Chrome: to samo co ^
//
//
//
package main
import (
"fmt"
"log"
"net/http"
socketio "github.com/googollee/go-socket.io" //alias do biblioteki importu
)
func main() {
fmt.Println("Hello World")
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.On("connection", func(so socketio.Socket) {
log.Println("New Connection")
//handle chat message to and front
so.Join("chat")
so.On("chat message", func(msg string) {
log.Println("Message Received From Client: " + msg)
so.BroadcastTo("chat", "chat message", msg)
})
})
//file system handler
fs := http.FileServer(http.Dir("static")) //do folderu
http.Handle("/", fs)
http.Handle("/socket.io/", server) //native html socket
log.Fatal(http.ListenAndServe(":5000", nil))
}

View File

@ -1,25 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Go WebSocket Tutorial</title>
</head>
<body>
<h2>Hello World</h2>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<!-- socket io library ^ -->
<script>
const socket = io('http://localhost:5000/socket.io/');
socket.emit("chat message", "Heloooooooooo")
socket.on("chat message", (msg) => {
console.log(msg);
})
</script>
</body>
</html>

View File

@ -1,13 +0,0 @@
package main
import (
"fmt"
)
func GenerateJWT() (string, error) {
fmt.Println("Generowanie JWT tokena dla klienta")
}
func ValidateToken() (string, error) {
fmt.Println("Walidacja Tokena dla tresci dostepnych tylko dla zalogowanych użytkowników")
}

View File

@ -1,21 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Jokeish App</title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdn.auth0.com/js/auth0/9.0/auth0.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/react@16.0.0/umd/react.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script type="text/babel" src="js/app.jsx"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="app"></div>
</body>
</html>

View File

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("hello world")
}

View File

@ -1,10 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<p>The date today is {{.Date}}</p>
<p>And the time is {{.Time}}</p>
</body>
</html>

View File

@ -1,15 +0,0 @@
package main
import (
"fmt"
"net/http"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func main() {
http.HandleFunc("/", helloWorld)
http.ListenAndServe(":8080", nil)
}

View File

@ -1,36 +0,0 @@
package main
import (
"html/template"
"log"
"net/http"
"time"
)
type PageVariables struct {
Date string
Time string
}
func main() {
http.HandleFunc("/", HomePage)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func HomePage(w http.ResponseWriter, r *http.Request) {
now := time.Now() // find the time right now
HomePageVars := PageVariables{ //store the date and time in a struct
Date: now.Format("02-01-2006"),
Time: now.Format("15:04:05"),
}
t, err := template.ParseFiles("homepage.html") //parse the html file homepage.html
if err != nil { // if there is an error
log.Print("template parsing error: ", err) // log it
}
err = t.Execute(w, HomePageVars) //execute the template and pass it the HomePageVars struct to fill in the gaps
if err != nil { // if there is an error
log.Print("template executing error: ", err) //log it
}
}

View File

@ -1,44 +0,0 @@
//testowanie w GO
//tutaj kod do przetestowania
//uwaga jak w wielu plikach jest package main, to test sie wywali na twarz
//pliki umieszcza wosobnych folderach jak tutaj
// λ go test
// # _/C_/Users/dp/Desktop/PracowaniaProgramowania/backend [_/C_/Users/dp/Desktop/PracowaniaProgramowania/backend.test]
// .\duplication.go:10:6: main redeclared in this block
// previous declaration at .\cw1.go:12:6
// .\echo1.go:8:6: main redeclared in this block
// previous declaration at .\duplication.go:10:6
// .\echo2.go:9:6: main redeclared in this block
// previous declaration at .\echo1.go:8:6
// .\hello.go:5:6: main redeclared in this block
// previous declaration at .\echo2.go:9:6
// .\serverTest.go:12:6: main redeclared in this block
// previous declaration at .\hello.go:5:6
// .\serverTest2.go:15:6: main redeclared in this block
// previous declaration at .\serverTest.go:12:6
// .\tut1.go:37:6: main redeclared in this block
// previous declaration at .\serverTest2.go:15:6
// .\tut2.go:13:6: Article redeclared in this block
// previous declaration at .\tut1.go:11:6
// .\tut2.go:19:6: Articles redeclared in this block
// previous declaration at .\tut1.go:17:6
// .\tut2.go:21:6: allArticles redeclared in this block
// previous declaration at .\tut1.go:19:44
// .\tut2.go:21:6: too many errors
// FAIL _/C_/Users/dp/Desktop/PracowaniaProgramowania/backend [build failed]
package main
import (
"fmt"
)
func Calculate(x int) (result int) {
result = x + 2
return result
}
func main() {
fmt.Println("Go testing tutorial")
result := Calculate(2)
fmt.Println(result)
}

View File

@ -1,69 +0,0 @@
//testowanie w GO
//tutaj testy
//uwaga jak w wielu plikach jest package main, to test sie wywali na twarz
//pliki umieszcza wosobnych folderach jak tutaj
// λ go test
// # _/C_/Users/dp/Desktop/PracowaniaProgramowania/backend [_/C_/Users/dp/Desktop/PracowaniaProgramowania/backend.test]
// .\duplication.go:10:6: main redeclared in this block
// previous declaration at .\cw1.go:12:6
// .\echo1.go:8:6: main redeclared in this block
// previous declaration at .\duplication.go:10:6
// .\echo2.go:9:6: main redeclared in this block
// previous declaration at .\echo1.go:8:6
// .\hello.go:5:6: main redeclared in this block
// previous declaration at .\echo2.go:9:6
// .\serverTest.go:12:6: main redeclared in this block
// previous declaration at .\hello.go:5:6
// .\serverTest2.go:15:6: main redeclared in this block
// previous declaration at .\serverTest.go:12:6
// .\tut1.go:37:6: main redeclared in this block
// previous declaration at .\serverTest2.go:15:6
// .\tut2.go:13:6: Article redeclared in this block
// previous declaration at .\tut1.go:11:6
// .\tut2.go:19:6: Articles redeclared in this block
// previous declaration at .\tut1.go:17:6
// .\tut2.go:21:6: allArticles redeclared in this block
// previous declaration at .\tut1.go:19:44
// .\tut2.go:21:6: too many errors
// FAIL _/C_/Users/dp/Desktop/PracowaniaProgramowania/backend [build failed]
package main
import "testing"
func TestCalculate(t *testing.T) {
if Calculate(2) != 4 {
t.Error("Expected 2+2 to equal 4")
}
// if Calculate(2) != 4 {
// t.Error("Expected 2+2 to equal 4")
// }
}
// func TestCalculate2(t *testing.T) {
// if Calculate(2) != 8 {
// t.Error("Expected 2+2 to equal 8")
// }
// }
func TestTableCalculate(t *testing.T) {
var tests = []struct {
input int
excpected int
}{
{2, 4},
{-1, 1},
{0, 2},
{9999, 10001},
}
//petelka foreach
for _, test := range tests {
if output := Calculate(test.input); output != test.excpected { //przypisanie a potem porownanie: 2 instrukcje w jednj linii - dlatego ;
t.Error("Tested Failed: {} inputted, {} expected , received {}", test.input, test.excpected, output) //jak .format() w py
}
}
}
//brak funkcji main o.Ó
//funkcje wykonuja sie po kolei jak w pythonie

View File

@ -1,39 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
//struktura artykuly
type Article struct {
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
type Articles []Article
func allArticles(w http.ResponseWriter, r *http.Request) {
articles := Articles{
Article{Title: "Test Title", Desc: "Test Description", Content: "Hello World"}, //json i szesceinne nawiasy!, przecinek na koniec
}
fmt.Println("Endpoint Hit: All Articles Endpoint")
json.NewEncoder(w).Encode(articles)
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Homepage Enpoint Hit")
}
func handleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/articles", allArticles)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func main() {
handleRequests()
}

View File

@ -1,49 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
//struktura artykuly
type Article struct {
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
type Articles []Article
func allArticles(w http.ResponseWriter, r *http.Request) {
articles := Articles{
Article{Title: "Test Title", Desc: "Test Description", Content: "Hello World"}, //json i szesceinne nawiasy!, przecinek na koniec
}
fmt.Println("Endpoint Hit: All Articles Endpoint")
json.NewEncoder(w).Encode(articles)
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Homepage Enpoint Hit")
}
func testPostArticles(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Test POST endpoint worker")
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/articles", allArticles).Methods("GET") //obsługa tylko GET
myRouter.HandleFunc("/articles", testPostArticles).Methods("POST") // -,- POST; wymagana nowa nazwa funkcji; ale ten sam url co wyzej ^
log.Fatal(http.ListenAndServe(":8081", myRouter))
}
func main() {
handleRequests()
}

View File

@ -1,39 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
//struktura artykuly
type Article struct {
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
type Articles []Article
func allArticles(w http.ResponseWriter, r *http.Request) {
articles := Articles{
Article{Title: "Test Title", Desc: "Test Description", Content: "Hello World"}, //json i szesceinne nawiasy!, przecinek na koniec
}
fmt.Println("Endpoint Hit: All Articles Endpoint")
json.NewEncoder(w).Encode(articles)
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Homepage Enpoint Hit")
}
func handleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/articles", allArticles)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func main() {
handleRequests()
}

View File

@ -1,20 +0,0 @@
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
files := http.FileServer(http.Dir("public"))
mux.Handle("static/", http.StripPrefix("static", files))
mux.HandleFunc("/")
server := &http.Server{
Addr: "0.0.0.0:808",
Handler: mux,
}
server.ListenAndServe()
}