Outils pour utilisateurs

Outils du site


blog

Go lang - les fichiers

Exemple lecture fichier texte

package main
 
import (
        "bufio"
        "fmt"
        "os"
)
 
func main() {
 
        file, err := os.Open("input.txt")
        if err != nil {
                panic(err)
        }
        defer func() {
                if err := file.Close(); err != nil {
                        panic(err)
                }
        }()
        scanner := bufio.NewScanner(file)
 
        // Iterate over each line
        for scanner.Scan() {
                line := scanner.Text()
                fmt.Println(line)
        }
 
}

Exemple d'écriture texte

func write_file(filename string, data string) {
	file, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := file.Close(); err != nil {
			panic(err)
		}
	}()
	_, err = file.WriteString(data)
	if err != nil {
		panic(err)
	}
 
}

Exemple de copie de fichier

Voir : https://opensource.com/article/18/6/copying-files-go

func copyFile(src, dest string) {
	input, err := ioutil.ReadFile(src)
	if err != nil {
		panic(err)
	}
 
	err = ioutil.WriteFile(dest, input, 0644)
	if err != nil {
		fmt.Println("Error creating", dest)
		panic(err)
	}
}

Fichier droits POSIX octal mode

Voir aussi :

	file, err := os.Lstat("/tmp/plop")
	if err != nil {
		panic(err)
	}
	mode := file.Mode()
	fmt.Printf("%s\n", mode)
	fmt.Printf("%o\n", mode)

Exemple lecture fichier CSV

package main
 
import (
        "encoding/csv"
        "fmt"
        "log"
        "os"
        "regexp"
)
 
func IsMatchingRegex(s string, regex string) bool {
        return regexp.MustCompile(regex).MatchString(s)
}
 
func main() {
        file, err := os.Open("data.csv")
        if err != nil {
                log.Fatal(err)
        }
        defer file.Close()
 
        // Read all records from the CSV file
        reader := csv.NewReader(file)
        reader.Comma = ';'
        records, err := reader.ReadAll()
        if err != nil {
                log.Fatal(err)
        }
 
 
        for _, record := range records[1:] {
                if IsMatchingRegex(record[0], "^#") {
                        continue
                }
 
                fmt.Println(record[0])
                fmt.Println(record[1])
        }
}

Exemple de calcul de hash d'un fichier

package main
 
import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
)
 
func hashFile(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", fmt.Errorf("failed to open file: %w", err)
	}
	defer file.Close()
 
	hasher := sha256.New()
	if _, err := io.Copy(hasher, file); err != nil {
		return "", fmt.Errorf("failed to hash file: %w", err)
	}
 
	return hex.EncodeToString(hasher.Sum(nil)), nil
}
 
func main() {
	hash, err := hashFile("/tmp/plop")
	if err != nil {
		panic(err)
	}
 
	fmt.Println(hash)
}
2026/05/14 20:40 · Jean-Baptiste

Go lang - regex

// Source - https://stackoverflow.com/a/41551456
// Posted by Mr_Pink, modified by community. See post 'Timeline' for change history
// Retrieved 2026-05-14, License - CC BY-SA 3.0
 
func IsMatchingRegex(s string, regex string) bool {
    return regexp.MustCompile(regex).MatchString(s)
}

FIXME

2026/05/14 20:11 · Jean-Baptiste

Go lang - goroutines

Pb sortie de main avant terminaisons des goroutines - Attendre la fin de toutes les goroutines avant de terminer le programme (la fonction main)

Afficher les résultats des goroutine de la plus rapide à la plus longue

Voir :

        ch1 := make(chan int)
        ch2 := make(chan int)
        go evenSum(1, 10, ch1)
        go squareSum(1, 10, ch2)
        for range 2 {
                select {
                case r1 := <-ch1:
                        fmt.Println(r1)
                case r2 := <-ch2:
                        fmt.Println(r2)
                }
        }

FIXME

2026/05/06 22:58 · Jean-Baptiste

Notes code dev - qualité de code - bonnes pratiques - sécu

Voir :

Points:

  • Testing
  • Negative testing (tests that should cause failures)
  • Detect and check unreachable code, e.g., via warning flags (static analysis)
  • Forbid misleading indentation (static analysis)
  • Detect duplicate lines in source code (static analysis)
  • Make access failure the default (static analysis)
  • Make your methods do only one thing
  • Use readable, descriptive variable names

4 tools:

  • ASan (Address Sanitizer)
  • MSan (Memory Sanitizer)
  • UBSan (Undefined Behaviour Sanitizer)
  • Valgrind
  • fuzzing

Source : https://www.cl.cam.ac.uk/~nk480/C1819/lecture5.pdf

Autres

  • AddressSanitizer (detects addressability issues) and LeakSanitizer (detects memory leaks)
  • ThreadSanitizer (detects data races and deadlocks) for C++ and Go
  • MemorySanitizer (detects use of uninitialized memory)
  • HWASAN, or Hardware-assisted AddressSanitizer, a newer variant of AddressSanitizer that consumes much less memory UBSan, or UndefinedBehaviorSanitizer

Source : https://github.com/google/sanitizers

Overflow
  • Heap overflow
  • Stack buffer overflow
  • Buffer overflow
  • Heap spraying
Ariane 5

Voir :

Nous avons :

  • Un buffer overflow
  • Une désactivation de la détection du buffer offerflow (unprotected code)
  • R6 - Aucune exception n'est levée
  • Un système redondant, mais avec le même code buggé
  • Ça n'avait pas été testé
  • R5 - Ça aurait pu être évité en rendant explicites les cas limites
The Inquiry Board's Recommendations

Source: https://www.esa.int/esapub/bulletin/bullet89/recom89.htm

The Inquiry Board's Recommendations

R1      Switch off the alignment function of the inertial reference
        system immediately after lift-off. More generally, no software
        function should run during flight unless it is needed.

R2      Prepare a test facility including as much real equipment
        as technically feasible, inject realistic input data, and perform
        complete, closed-loop, system testing. Complete simulations must
        take place before any mission. A high test coverage has to be
        obtained.

R3      Do not allow any sensor, such as the inertial reference
        system, to stop sending best-effort data.

R4      Organise, for each item of equipment incorporating
        software, a specific software qualification review. The
        Industrial Architect shall take part in these reviews and report
        on complete system testing performed with the equipment. All
        restrictions on use of the equipment shall be made explicit for
        the Review Board. Make all critical software a Configuration
        Controlled Item.


R5      Review all flight software (including embedded software),
        and in particular:

    Identify all implicit assumptions made by the code and its justification documents on the values of quantities provided by the equipment. Check these assumptions against the restrictions on use of the equipment.

    Verify the range of values taken by any internal or communication variables in the software.

    Solutions to potential problems in the onboard computer software, paying particular attention to onboard computer switchover, shall be proposed by the Project Team and reviewed by a group of external experts, who shall report to the onboard- computer Qualification Board.


R6      Wherever technically feasible, consider confining
        exceptions to tasks and devise backup capabilities.

R7      Provide more data to the telemetry upon failure of any
        component, so that recovering equipment will be less essential.

R8      Reconsider the definition of critical components, taking
        failures of software origin into account (particularly single-
        point failures).

R9      Include external (to the project) participants when
        reviewing specifications, code and justification documents. Make
        sure that these reviews consider the substance of arguments,
        rather than check that verifications have been made.

R10     Include trajectory data in specifications and test
        requirements.

R11     Review the test coverage of existing equipment and extend
        it where deemed necessary.

R12     Give the justification documents the same attention as
        code. Improve the technique for keeping code and its
        justifications consistent.

R13     Set up a team that will prepare the procedure for
        qualifying software, propose stringent rules for confirming such
        qualification, and ascertain that specification, verification and
        testing of software are of a consistently high quality in the
        Ariane-5 Programme. Inclusion of external RAMS (Reliability,
        Availability, Maintainability, Safety) experts is to be
        considered.

R14     A more transparent organisation of the cooperation among
        the partners in the Ariane-5 Programme must be considered. Close
        engineering cooperation, with clear-cut authority and
        responsibility, is needed to achieve system coherence, with
        simple and clear interfaces between partners.

FIXME

2026/05/04 20:51 · Jean-Baptiste
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki