Rosetta 2
Posted on September 2, 2022
Tags: codeetc
1 build datatype
type Bitcoin int
x := Bitcoin(10)data Bitcoin = Bitcoin Inttypedef unsigned int Bitcoin;2 Insertion sort
insertionSort[a_List] := Module[
{A = a},
For[i = 2, i <= Length[A], i++,
value = A[[i]];
j = i - 1;
While[j >= 1 && A[[j]] > value,
A[[j + 1]] = A[[j]];
j--;];
A[[j + 1]] = value;];
A
]
insertionSort@{ 2, 1, 3, 5}3 Http server
package main
import(
"net/http"
"fmt"
"strings"
)
type MyServer struct {
}
func (p *MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
player := strings.TrimPrefix(r.URL.Path, "/players/")
s := fmt.Sprintf("<h1> %s </h1>", player)
fmt.Fprint(w, s)
}
func main(){
server := &MyServer{}
http.ListenAndServe(":5000", server)
}override Muxer
package main
import(
"net/http"
"fmt"
"strings"
)
type MyServer struct {
}
func (p MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
router := http.NewServeMux()
router.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
content := "AHHH"
s := fmt.Sprintf("<h1> %s </h1>", content)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, s)
}))
router.Handle("/players/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
player := strings.TrimPrefix(r.URL.Path, "/players/")
s := fmt.Sprintf("<h1> %s </h1>", player)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, s)
}))
router.ServeHTTP(w, r)
}
func main(){
server := MyServer{}
http.ListenAndServe(":5000", server)
}3.1 Dapr
package main
import(
"net/http"
// "fmt"
// "strings"
"encoding/json"
)
type Subscription struct {
PubSubName string `json:"pubsubname"`
Topic string `json:"topic"`
Route string `json:"route"`
}
type MyServer struct {
}
func (p MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
subscriptions := []Subscription{
{"a","b","c"},
{"d","e","f"},
}
router := http.NewServeMux()
router.Handle("/dapr/subscribe/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(subscriptions)
}))
router.ServeHTTP(w, r)
}
func main(){
server := MyServer{}
http.ListenAndServe(":5000", server)
}package main
import(
"net/http"
"log"
// "fmt"
// "strings"
"encoding/json"
)
type Subscription struct {
PubSubName string `json:"pubsubname"`
Topic string `json:"topic"`
Route string `json:"route"`
}
type MyServer struct {
}
func (p MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
subscriptions := []Subscription{
{"a","b","c"},
{"d","e","f"},
}
router := http.NewServeMux()
router.Handle("/dapr/subscribe/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
json.NewEncoder(w).Encode(subscriptions)
}
}))
for _,i := range subscriptions{
router.Handle(i.PubSubName, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
log.Println(r.Body)
}
}))
}
router.ServeHTTP(w, r)
}
func main(){
server := MyServer{}
http.ListenAndServe(":5000", server)
}